package com.example.yoga.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.yoga.entity.*;
import com.example.yoga.service.*;
import com.example.yoga.util.JsonResult;
import com.example.yoga.util.PageDataResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liwenkai
 * @since 2021-02-03
 */
@RestController
@RequestMapping("/combo")
public class ComboController {

    @Autowired
    private IComboService comboService;

    @Autowired
    private IUserComboService userComboService;

    @Autowired
    private IUserCardService userCardService;

    @Autowired
    private ICardService cardService;

    @Autowired
    private IUsercomboStatusService usercomboStatusService;

    @Autowired
    private IPayRecordService payRecordService;


    /**
     * getComboCount
     */
    @RequestMapping(value = "/getComboCount",method = RequestMethod.GET)
    public JsonResult<List> getComboCount(){
        /**
         * 分别获取三种套餐的销售量
         */
        List<Map<String, Object>> list = comboService.getComboCount();
        return new JsonResult<>(2000,list);
    }

    /**
     * 获取系统内的课程总数
     */
    @RequestMapping(value = "/getTotalCombo",method = RequestMethod.GET)
    public JsonResult<Integer> getTotalCombo(){
        int totalCombo = comboService.getTotalCombo();
        return new JsonResult<>(2000,totalCombo);
    }

    /**
     * 购买套餐记录
     */
    @RequestMapping("/getComboRecord")
    public PageDataResult getComboRecord(Integer userid, Integer pageIndex, Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        QueryWrapper<UserCombo> userComboQueryWrapper = new QueryWrapper<>();
        userComboQueryWrapper.eq("userId",userid);
        //得到的套餐记录
        List<UserCombo> list = userComboService.list(userComboQueryWrapper);
        System.out.println(list);
        if (list.size()>0){
            PageInfo<UserCombo> pageInfo = new PageInfo<>(list);
            PageDataResult pdr = new PageDataResult();
            pdr.setList(pageInfo.getList());
            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
            return pdr;
        }
       return null;
    }


    /**
     * 用户申请办理卡
     */
    @RequestMapping(value = "/applyCard",method = RequestMethod.GET)
    public JsonResult<Void> applyCard(Integer userid,Integer comboid) {
        //测试是否传入数据
        System.out.println(userid+"lllllllllllllll"+comboid);
        //将数据填入到usercombo_status表中
        UsercomboStatus usercomboStatus = new UsercomboStatus();
        usercomboStatus.setUserid(userid);
        usercomboStatus.setComboid(comboid);
        usercomboStatus.setApplytime(new Date());
        usercomboStatus.setStatus("待审核");
        boolean b = usercomboStatusService.save(usercomboStatus);
        if(b){
            return new JsonResult<>(2000,"已提交申请，待审核！");
        }
        return new JsonResult<>(4000,"申请失败，请重新提交申请！");
    }

    /**
     * getCheckCardList 获取申请卡的记录
     */
    @RequestMapping("/getCheckCardList")
    public PageDataResult getCheckCardList(String name, Integer pageIndex, Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        //不做查询了
       if (name!=null){

       }
       //联查， 用户购买套餐的记录
        List<UsercomboStatusVo> list = usercomboStatusService.getCardComboList();
        //查询条件为空，直接获取所有记录
//        QueryWrapper<UsercomboStatus> usercomboStatusQueryWrapper = new QueryWrapper<>();
//       usercomboStatusQueryWrapper.orderByDesc("userId");
//        List<UsercomboStatus> list = usercomboStatusService.list(usercomboStatusQueryWrapper);
        System.out.println(list);
        if (list.size()>0){
            PageInfo<UsercomboStatusVo> pageInfo = new PageInfo<>(list);
            PageDataResult pdr = new PageDataResult();
            pdr.setList(pageInfo.getList());
            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
            return pdr;
        }
        return null;
    }
    /**
     * 办卡
     */
    @RequestMapping(value = "/makeCard",method = RequestMethod.GET)
    public JsonResult<Void> makeCard(Integer userid,Integer comboid,Integer ucsid){

        //添加之后，我们应该将支付记录到payrecord中
//        QueryWrapper<Combo> wrapper = new QueryWrapper<>();
//        wrapper.eq("comboId",comboid);
//        Combo combo = comboService.getOne(wrapper);
//
//        PayRecord payRecord = new PayRecord();
//        payRecord.setPayno(UUID.randomUUID().toString().replaceAll("-",""));
//        payRecord.setUserid(userid);
//        payRecord.setPayamount(combo.getComboprice().doubleValue());
//        payRecord.setPaydate(new Date());
//        payRecord.setPaystatus("已审核");
//        payRecordService.save(payRecord);
        //////////////////////////////////////////
        /////////////////////////////////////////



        //根据ucsid来改变这一条记录
        UsercomboStatus usercomboStatus = usercomboStatusService.getById(ucsid);
        usercomboStatus.setChecktime(new Date());
        usercomboStatus.setStatus("已审核");
        usercomboStatusService.updateById(usercomboStatus);


        //直接添加到用户套餐记录表中
        UserCombo userCombo = new UserCombo();
        userCombo.setUserid(userid);
        userCombo.setComboid(comboid);
        userCombo.setBuytime(new Date());
        //根据用户id来查询usercard关联表，看是否该用户已经办理过卡
        QueryWrapper<UserCard> userCardQueryWrapper = new QueryWrapper<>();
        userCardQueryWrapper.eq("userId",userid);
        List<UserCard> list = userCardService.list(userCardQueryWrapper);
        if (list.size()>0){
            //说明该用户下有卡,找出这个卡,则进行延期操作
            Card card = cardService.getById(list.get(0).getCardid());
            //找出购买的套餐
            if(comboid==1){
                //这是月卡，增加一个月
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date dt = card.getEndDate();
                Date d=new Date();
                int result=d.compareTo(dt);
                if (result>0){
                    //证明当前时间大于卡的到期时间，说明卡已过期，延期操作要从当前时间算起
                    card.setBeginDate(new Date());
                    dt=new Date();
                }
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(dt);
                rightNow.add(Calendar.MONTH, 1);
//                Date dt1 = rightNow.getTime();
//                String reStr = sdf.format(dt1);
                card.setEndDate(rightNow.getTime());
                userCombo.setEndtime(rightNow.getTime());
            }
            if (comboid==2){
                //这是月卡，增加三个月
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date dt = card.getEndDate();
                Date d=new Date();
                int result=d.compareTo(dt);
                if (result>0){
                    //证明当前时间大于卡的到期时间，说明卡已过期，延期操作要从当前时间算起
                    card.setBeginDate(new Date());
                    dt=new Date();
                }
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(dt);
                rightNow.add(Calendar.MONTH, 3);
//                Date dt1 = rightNow.getTime();
//                String reStr = sdf.format(dt1);
                card.setEndDate(rightNow.getTime());
                userCombo.setEndtime(rightNow.getTime());
            }
            if(comboid==3){
                //这是年卡，增加一年
                Date dt = card.getEndDate();
                Date d=new Date();
                int result=d.compareTo(dt);
                if (result>0){
                    //证明当前时间大于卡的到期时间，说明卡已过期，延期操作要从当前时间算起
                    card.setBeginDate(new Date());
                    dt=new Date();
                }
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(dt);
                rightNow.add(Calendar.YEAR, 1);
//                Date dt1 = rightNow.getTime();
//                String reStr = sdf.format(dt1);
                card.setEndDate(rightNow.getTime());
                userCombo.setEndtime(rightNow.getTime());
            }
            QueryWrapper<Card> cardQueryWrapper = new QueryWrapper<>();
            cardQueryWrapper.eq("cardId",list.get(0).getCardid());
            cardService.update(card,cardQueryWrapper);
            userComboService.save(userCombo);
            return new JsonResult<>(2000,"延期成功");
        }
        //根据套餐id，添加到card中
        //创建一个card对象
        Card card = new Card();
        card.setCardno(UUID.randomUUID().toString().replaceAll("-",""));
        card.setBeginDate(new Date());
        if (comboid==1){
            Date dt = new Date();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, 1);
            card.setEndDate(rightNow.getTime());
            userCombo.setEndtime(rightNow.getTime());
        }
        if(comboid==2){
            Date dt = new Date();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, 3);
            card.setEndDate(rightNow.getTime());
            userCombo.setEndtime(rightNow.getTime());
        }
        if (comboid==3){
            Date dt = new Date();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.YEAR, 1);
            card.setEndDate(rightNow.getTime());
            userCombo.setEndtime(rightNow.getTime());
        }
        cardService.save(card);
        userComboService.save(userCombo);
        //从数据库读取到刚刚添加的cardid
        QueryWrapper<Card> cardWrapper = new QueryWrapper<>();
        cardWrapper.eq("cardNo",card.getCardno());
        Card one = cardService.getOne(cardWrapper);
        //添加usercard中间表
        UserCard userCard = new UserCard();
        userCard.setUserid(userid);
        userCard.setCardid(one.getCardid());
        userCardService.save(userCard);
        return new JsonResult<>(2000,"添加新卡成功！");
    }




    /**
     * 添加套餐
     */
    @RequestMapping("/addCombo")
    public JsonResult<Void> addCombo(@RequestBody Combo combo){
        System.out.println(combo+"***********8888");
        if(combo!=null){
            boolean b = comboService.save(combo);
            if(b){
                return new JsonResult<>(2000,"添加成功");
            }
        }
        return new JsonResult<>(4000,"添加失败");
    }

    /**
     * 删除套餐
     */
    @RequestMapping("/delCombo")
    public JsonResult<List> delCombo(Integer id){
        //判断套餐下面有没有这个套餐还未到期限的用户，如果有，不能删除;没有，则删除
        //ge是大于等于，le是小于等于
        QueryWrapper<UserCombo> wrapper = new QueryWrapper<>();
        wrapper.eq("comboId",id);
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        wrapper.ge("endtime",date);
        wrapper.le("buytime",date);
        List<UserCombo> userComboList = userComboService.list(wrapper);
        if(userComboList.size()>0){
            return new JsonResult<>(2000,"不能删除，这个套餐有用户正在使用");
        }
        boolean b = comboService.removeById(id);
        if (b){
            return new JsonResult<>(2000,"删除成功！");
        }
        return new JsonResult<>(2000,"删除失败！");
    }

    /**
     * 修改套餐
     */
    @RequestMapping("updateCombo")
    public JsonResult<Void> updateCombo(@RequestBody Combo combo){
        Integer comboid = combo.getComboid();
        if(comboid!=null){
            QueryWrapper<Combo> wrapper = new QueryWrapper<>();
            wrapper.eq("comboId",comboid);
            boolean b = comboService.update(combo, wrapper);
            if (b){
                return new JsonResult<>(2000,"修改成功！");
            }
        }
        return new JsonResult<>(4000,"修改失败！");
    }

    /**
     * 按id查询套餐
     */
    @RequestMapping("queryById")
    public JsonResult<Combo> queryById(Integer id){
        QueryWrapper<Combo> wrapper = new QueryWrapper<>();
        wrapper.eq("comboId",id);
        Combo one = comboService.getOne(wrapper);
        if (one!=null){
            return new JsonResult<>(2000,one);
        }
        return new JsonResult<>(4000,"没有查到记录！");
    }

    /**
     * 查询所有套餐
     */
    @RequestMapping("queryAll")
    public JsonResult<List> queryAll(){
        List<Combo> comboList = comboService.list();
        if (comboList.size()>0){
            return new JsonResult<>(2000,comboList);
        }
        return new JsonResult<>(4000,"没有查到记录！");
    }

    /**
     * 查询个人套餐
     */
    @RequestMapping("/queryPersonalCombo")
    public JsonResult<List> queryPersonalCombo(String username, HttpSession session){
        User user = (User) session.getAttribute(username);
        QueryWrapper<UserCombo> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",user.getUserid());
        //根据用户套餐关联表查询出该用户下已办理的所有套餐，
        // 注意这里需要把得到的套餐id转换为套餐名，还需要进行一次查询，并且遍历列表，待完善
        List<UserCombo> list = userComboService.list(wrapper);
        if (list.size()<=0){
            return new JsonResult<>(4000,"没有该用户信息");
        }
        //得到套餐表里的套餐列表
        List<Combo> comboList = comboService.list();
        //封装的结果列表
        List<Combo> resultComboList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < comboList.size(); j++) {
                if (list.get(i).getComboid().equals(comboList.get(j).getComboid())){
                    resultComboList.add(comboList.get(j));
                }
            }
        }
        return new JsonResult<>(2000,resultComboList);
    }
}

